#!/bin/bash

cat <<EOF
请选择 Amlogic Box 的类型:
-----------------------------------------------------------------------------------
1. Phicomm N1 (斐讯N1 或 S905X、S905D等盒子), 默认跳过 EMMC 的前面 700MB
2. X96 Max, X96 Max+ (或与之相当的 S905X2、S905X3 盒子)，默认跳过 EMMC 的前面 1350MB
3. 自定义要跳过的空间(单位: MB)
0. 我看错了, 不刷了
-----------------------------------------------------------------------------------
EOF

SKIP=700
BOOT=256

read select
case $select in 
	1) SKIP=700;;
        2) SKIP=1350;;
	3) echo -ne "请输入要跳过的大小(MB), 只能是 (68-2048) 范围(如果数值不合理，有变砖可能) : "
	   read skip
	   if [ -z "$skip" ];then
		   echo "输入错误"
		   exit 1
	   fi
	   if (( $skip >= 68  && $skip <= 2048 ));then
		   SKIP=$skip
	   else
		   echo "输入错误: $skip"
		   exit 1
	   fi
	   ;;
	*) exit;;
esac

echo "SKIP = $SKIP MB"
systemctl stop armbian-resize-filesystem.service
systemctl disable armbian-resize-filesystem.service

fstype=$1
case $fstype in 
	  xfs) fstype=xfs;;
	btrfs) fstype=btrfs;;
	 f2fs) fstype=f2fs;;
	    *) fstype=ext4;;
esac

echo "Start script create MBR and filesystem"

hasdrives=$(lsblk | grep -oE '(mmcblk[0-9])' | sort | uniq)
if [ "$hasdrives" = "" ]
then
	echo "UNABLE TO FIND ANY EMMC OR SD DRIVES ON THIS SYSTEM!!! "
	exit 1
fi
avail=$(lsblk | grep -oE '(mmcblk[0-9]|sda[0-9])' | sort | uniq)
if [ "$avail" = "" ]
then
	echo "UNABLE TO FIND ANY DRIVES ON THIS SYSTEM!!!"
	exit 1
fi
runfrom=$(lsblk | grep /$ | grep -oE '(mmcblk[0-9]|sda[0-9])')
if [ "$runfrom" = "" ]
then
	echo " UNABLE TO FIND ROOT OF THE RUNNING SYSTEM!!! "
	exit 1
fi
emmc=$(echo $avail | sed "s/$runfrom//" | sed "s/sd[a-z][0-9]//g" | sed "s/ //g")
if [ "$emmc" = "" ]
then
	echo " UNABLE TO FIND YOUR EMMC DRIVE OR YOU ALREADY RUN FROM EMMC!!!"
	exit 1
fi
if [ "$runfrom" = "$avail" ]
then
	echo " YOU ARE RUNNING ALREADY FROM EMMC!!! "
	exit 1
fi
if [ $runfrom = $emmc ]
then
	echo " YOU ARE RUNNING ALREADY FROM EMMC!!! "
	exit 1
fi
if [ "$(echo $emmc | grep mmcblk)" = "" ]
then
	echo " YOU DO NOT APPEAR TO HAVE AN EMMC DRIVE!!! "
	exit 1
fi

DEV_EMMC="/dev/mmcblk1"

echo $DEV_EMMC

# 判断内核版本是否 >= 5.10
KERNEL_VERSION=$(uname -r)
K_VER=$(echo "$KERNEL_VERSION" | cut -d '.' -f1)
K_MAJ=$(echo "$KERNEL_VERSION" | cut -d '.' -f2)

if [ $K_VER -eq 5 ];then
	if [ $K_MAJ -ge 10 ];then
		K510=1
	else
		K510=0
	fi
elif [ $K_VER -gt 5 ];then
	K510=1
else
	K510=0
fi

echo "Start backup u-boot default"
dd if="${DEV_EMMC}" of=/root/u-boot-default-aml.img bs=1M count=4 conv=fsync
exists_pts=$(parted ${DEV_EMMC} print |grep 'primary'|wc -l)
if [ $exists_pts -gt 0 ];then
    i=1
    while [ $i -le $exists_pts ]
    do
        parted -s ${DEV_EMMC} rm $i 2>/dev/null
        let i=i+1
    done
fi
dd if=/dev/zero of=${DEV_EMMC} bs=512 count=1 conv=fsync

echo "Start create MBR and partittion"
parted -s "${DEV_EMMC}" mklabel msdos 2>/dev/null
parted -s "${DEV_EMMC}" mkpart primary fat32 $((SKIP*1024*1024))b $(( (SKIP+BOOT)*1024*1024 - 1 ))b 2>/dev/null
parted -s "${DEV_EMMC}" mkpart primary ext4 $(( (SKIP+BOOT)*1024*1024 ))b 100% 2>/dev/null

echo "Start restore u-boot"
dd if=/root/u-boot-default-aml.img of="${DEV_EMMC}" conv=fsync bs=1 count=442 
dd if=/root/u-boot-default-aml.img of="${DEV_EMMC}" conv=fsync bs=512 skip=1 seek=1

sync
echo "Done"

echo "Start copy system for eMMC."

mkdir -p /ddbr
chmod 777 /ddbr

PART_BOOT="${DEV_EMMC}p1"
PART_ROOT="${DEV_EMMC}p2"
DIR_INSTALL="/ddbr/install"

if [ -d $DIR_INSTALL ] ; then
    rm -rf $DIR_INSTALL
fi
mkdir -p $DIR_INSTALL

if grep -q $PART_BOOT /proc/mounts ; then
    echo "Unmounting BOOT partiton."
    umount -f $PART_BOOT
fi
echo -n "Formatting BOOT partition..."
mkfs.vfat -n "BOOT_EMMC" $PART_BOOT
echo "done."

mount -o rw $PART_BOOT $DIR_INSTALL

echo -n "Copying BOOT..."
cp -r /boot/* $DIR_INSTALL && sync
rm -rf $DIR_INSTALL/'System Volume Information' 2>/dev/null
echo "done."

echo -n "Edit init config..."
lines=$(wc -l < $DIR_INSTALL/uEnv.txt)
let lines=lines-1
head -n $lines $DIR_INSTALL/uEnv.txt > $DIR_INSTALL/uEnv-emmc.txt

case $fstype in 
	btrfs) cat >> $DIR_INSTALL/uEnv-emmc.txt <<EOF
APPEND=root=LABEL=ROOTFS_EMMC rootfstype=btrfs rootflags=compress=zstd console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
;;
          xfs) cat >> $DIR_INSTALL/uEnv-emmc.txt <<EOF
APPEND=root=LABEL=ROOTFS_EMMC rootfstype=xfs rootflags=rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
;;
         f2fs) cat >> $DIR_INSTALL/uEnv-emmc.txt <<EOF
APPEND=root=LABEL=ROOTFS_EMMC rootfstype=f2fs rootflags=rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
;;
         ext4) cat >> $DIR_INSTALL/uEnv-emmc.txt <<EOF
APPEND=root=LABEL=ROOTFS_EMMC rootflags=data=writeback rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0 cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory swapaccount=1
EOF
;;
esac

mv $DIR_INSTALL/uEnv-emmc.txt $DIR_INSTALL/uEnv.txt
touch $DIR_INSTALL/uEnv.txt
cp -v $DIR_INSTALL/uEnv.txt /root/uEnv.emmc
if [ $K510 -eq 1 ];then
    cp -v $DIR_INSTALL/uEnv.txt /boot/uEnv.emmc
fi
cp -v /boot/uEnv.txt  /root/uEnv.sd
rm $DIR_INSTALL/s9*
rm $DIR_INSTALL/aml*
mv -f $DIR_INSTALL/boot-emmc.ini $DIR_INSTALL/boot.ini
sed -e "s/u-boot.ext/u-boot.emmc/g" -i "$DIR_INSTALL/boot.ini"
mv -f $DIR_INSTALL/boot-emmc.scr $DIR_INSTALL/boot.scr
mv -f $DIR_INSTALL/boot-emmc.cmd $DIR_INSTALL/boot.cmd
if [ -f /boot/u-boot.ext ] ; then
    if [ $K510 -eq 1 ];then
        cp -v $DIR_INSTALL/u-boot.ext $DIR_INSTALL/u-boot.emmc
    else
        mv -f $DIR_INSTALL/u-boot.sd $DIR_INSTALL/u-boot.emmc
    fi
fi
sync
echo "done."

umount $DIR_INSTALL

if grep -q $PART_ROOT /proc/mounts ; then
    echo "Unmounting ROOT partiton."
    umount -f $PART_ROOT
fi

echo "Formatting ROOT partition..."
case $fstype in 
	btrfs) mkfs.btrfs -f -L ROOTFS_EMMC -m single $PART_ROOT
		;;
	  xfs) mkfs.xfs -f -L ROOTFS_EMMC $PART_ROOT
		;;
	 f2fs) mkfs.f2fs -f -l ROOTFS_EMMC $PART_ROOT
		;;
	 ext4) mkfs.ext4 -F -L ROOTFS_EMMC $PART_ROOT
		;;
esac
echo "done."

echo "Copying ROOTFS."

case $fstype in 
	btrfs) mount -t btrfs -o compress=zstd $PART_ROOT $DIR_INSTALL
		;;
	  xfs) mount -t xfs $PART_ROOT $DIR_INSTALL
		;;
         f2fs) mount -t f2fs $PART_ROOT $DIR_INSTALL
		;;
	 ext4) mount -t ext4 $PART_ROOT $DIR_INSTALL
		;;
esac

cd /
echo "Copy BIN"
tar -cf - bin | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy BOOT"
mkdir -p $DIR_INSTALL/boot
#tar -cf - boot | (cd $DIR_INSTALL; tar -xpf -)
echo "Create DEV"
mkdir -p $DIR_INSTALL/dev
#tar -cf - dev | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy ETC"
tar -cf - etc | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy HOME"
tar -cf - home | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy LIB"
tar -cf - lib | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy LIB64"
tar -cf - lib64 | (cd $DIR_INSTALL; tar -xpf -)
echo "Create MEDIA"
mkdir -p $DIR_INSTALL/media
#tar -cf - media | (cd $DIR_INSTALL; tar -xpf -)
echo "Create MNT"
mkdir -p $DIR_INSTALL/mnt
#tar -cf - mnt | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy OPT"
tar -cf - opt | (cd $DIR_INSTALL; tar -xpf -)
echo "Create PROC"
mkdir -p $DIR_INSTALL/proc
echo "Copy ROOT"
tar -cf - root | (cd $DIR_INSTALL; tar -xpf -)
echo "Create RUN"
mkdir -p $DIR_INSTALL/run
echo "Copy SBIN"
tar -cf - sbin | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy SELINUX"
tar -cf - selinux | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy SRV"
tar -cf - srv | (cd $DIR_INSTALL; tar -xpf -)
echo "Create SYS"
mkdir -p $DIR_INSTALL/sys
echo "Create TMP"
mkdir -p $DIR_INSTALL/tmp
echo "Copy USR"
tar -cf - usr | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy VAR"
tar -cf - var | (cd $DIR_INSTALL; tar -xpf -)
sync

echo "Copy fstab"

rm $DIR_INSTALL/etc/fstab
case $fstype in
	btrfs) cat > $DIR_INSTALL/etc/fstab<<EOF
/dev/root       /               btrfs           defaults,noatime,compress=zstd		0 1
EOF
;;
	  xfs) cat > $DIR_INSTALL/etc/fstab<<EOF
/dev/root       /               xfs             defaults,noatime                        0 1
EOF
;;
	 f2fs) cat > $DIR_INSTALL/etc/fstab<<EOF
/dev/root       /               f2fs            defaults,noatime                        0 1
EOF
;;
	 ext4) cat > $DIR_INSTALL/etc/fstab<<EOF
/dev/root       /               ext4            defaults,noatime,errors=remount-ro     	0 1
EOF
;;
esac

if [ $K510 -eq 1 ];then
	BOOT_LABEL="BOOT"
else
	BOOT_LABEL="BOOT_EMMC"
fi

cat >> $DIR_INSTALL/etc/fstab <<EOF
LABEL=${BOOT_LABEL} /boot           vfat            defaults                                0 0
tmpfs           /tmp            tmpfs           defaults,nosuid                         0 0
EOF
echo "done"
	
rm $DIR_INSTALL/root/install-to-emmc.sh
rm -f $DIR_INSTALL/root/fstab
rm $DIR_INSTALL/usr/bin/ddbr

cd /
sync

umount $DIR_INSTALL

echo "*******************************************"
echo "Complete copy OS to eMMC "
echo "*******************************************"

if [ $K510 -eq 1 ];then
	echo "由于内核版本 >= 5.10, 只能用 tf卡 或 U盘 启动，因此请不要拔掉启动介质！"
	echo "备份 /boot/uEnv.txt 至  /boot/uEnv.sd(如果将来需要进入救援模式，可以把 /boot/uEnv.sd 改名成/boot/uEnv.txt"
	cp -v /boot/uEnv.txt /boot/uEnv.sd
	echo "把 /boot/uEnv.emmc 改名为 /boot/uEnv.txt"
	cp -v /boot/uEnv.emmc /boot/uEnv.txt
	sync
	echo "完成"
fi
echo "安装过程结束，请重启"
